<?php foreach($paymentdtl as $pd): ?>
    <div class="ibox float-e-margins">
        <div class="ibox-title" style="border: none;">
            <h5 style="color: #00afef"><i>Payment Details</i></h5>
        </div>
        <div class="ibox-content">
            <form class="form-horizontal">
                <div class="form-group">
                <label class="col-lg-4 control-label">Account Name</label>
                    <div class="col-lg-5">
                        <input readonly type="text" class="form-control" value="<?php echo $pd->acct_name; ?>">
                    </div>
                </div>
                <div class="form-group">
                <label class="col-lg-4 control-label">Account #</label>
                    <div class="col-lg-5">
                        <input readonly type="number" class="form-control" value="<?php echo $pd->acct_num; ?>">
                    </div>
                </div>
                <div class="form-group">
                <label class="col-lg-4 control-label">Invoice ID</label>
                    <div class="col-lg-5">
                        <input readonly type="number" class="form-control" value="<?php echo $pd->invoice_id; ?>">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">Pay Amount</label>
                    <div class="col-lg-5">
                        <input readonly type="number" value="<?php echo $pd->pay_amount; ?>" class="form-control">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">Balance</label>
                    <div class="col-lg-5">
                        <input type="hidden" name="balance2" value="" class="form-control">
                        <input readonly type="number" value="<?php echo $pd->balance; ?>" class="form-control">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">Receipt Number</label>
                    <div class="col-lg-5">
                        <button type="button" class="btn btn-link rec-link" id="<?php echo $pd->receipt_number; ?>"><?php echo $pd->receipt_number; ?></button>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">Payment Type</label>
                    <div class="col-lg-5">
                        <input readonly value="<?php echo $pd->payment_type; ?>" type="text" class="form-control">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">Receipt Date</label>
                    <div class="col-lg-5">
                        <input readonly value="<?php echo $pd->receipt_date; ?>" type="text" class="form-control">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">Reference</label>
                    <div class="col-lg-5">
                        <input readonly type="text" value="<?php echo $pd->reference; ?>" class="form-control">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">Remarks</label>
                    <div class="col-lg-5">
                        <input readonly type="text" value="<?php echo $pd->remarks; ?>" name="remarks" class="form-control">
                    </div>
                </div>
            </form>
        </div> <!-- ibox content END -->
    </div>
<?php endforeach; ?>
    <div class="modal inmodal" id="receipt2" tabindex="-1" role="dialog" aria-hidden="true">
        <div style="width: 750px;" class="modal-dialog">
            <div class="modal-content animated fadeInUp">
                    <div class="modal-body">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                        <h2 style="color: #00afef"><i>Payment Details</i></h2>
                        <br>
                        <form class="form-horizontal" id="receipt_payment_form">
                            <div class="form-inline form-group">
                                <label class="col-sm-2 control-label">Receipt No</label>
                                <div class="col-lg-3">
                                    <input readonly type="text" id="receipt_number" class="form-control">
                                </div>
                                <label class="col-sm-3 control-label">Payment Type</label>
                                <div class="col-sm-3">
                                    <input type="hidden" name="totalcost" value="">
                                    <input readonly type="text" id="payment_type" class="form-control">
                                </div>
                            </div>
                            <div class="form-inline form-group">
                                <label class="col-sm-2 control-label">Receipt Date</label>
                                <div class="col-lg-3">
                                    <input readonly type="text" id="receipt_date" class="form-control">
                                </div>
                                <label class="col-sm-3 control-label">Account No</label>
                                <div class="col-sm-3">
                                    <input readonly type="text" id="acct_no" class="form-control">
                                </div>
                            </div>
                            <div class="form-group form-inline">
                                <label class="col-sm-2 control-label">Reference</label>
                                <div class="col-lg-3">
                                    <input readonly type="text" id="reference" class="form-control">
                                </div>
                            </div>
                        </form>
                        <br>
                        <center>
                        <div id="payment_details_body">
                        <table class="c-table">
                            <thead>
                                <tr>
                                    <th>Invoice Number</th>
                                    <th>Invoice Type</th>
                                    <th>Invoice Date</th>
                                    <th>Due Date</th>
                                    <th>Total Amt</th>
                                    <th>Paid Amt</th>
                                    <th>Balance</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td align="right">151012345</td>
                                    <td>Water BILL</td>
                                    <td>5-Dec-15</td>
                                    <td>6-Dec-15</td>
                                    <td align="right">1,000.00</td>
                                    <td align="right">1,500.00</td>
                                    <td align="right">500.00</td>
                                </tr>
                            </tbody>
                        </table>
                        </div>
                        <br>
                        <div style="width: 250px;">
                           <button type="button" class="btn btn-success btn-block btn-md m-t-n-xs" id="search_payment"><i class="fa fa-print fa-fw"></i> Print Receipt</button> 
                        </div>
                        </center><br>
                        <br>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
    $(document).ready(function() {
        $('.i-checks').iCheck({
            checkboxClass: 'icheckbox_square-green hover',
            radioClass: 'iradio_square-green'
        });
        $('#payment_details_body').slimScroll({
            height: '200px',
            railVisible: true
        });

        $('#payment_process_form input[name=receipt_date]').val(new Date().toJSON().slice(0,10));

        var tmp = 0;
        var sum = 0;
        var tmp_amount = [];
        var invoices = [];
        $('table').on('change','input[type=checkbox]',function(){
            //var amount = parseFloat($(this).closest('tr').children('.amount').text());
            var amount =  parseFloat(getbal($(this).closest('tr').children('.invoice_id').text()));
            console.log(amount);
            var invid = $(this).closest('tr').children('.invoice_id').text();
            var s_amount = $('#payment_process_form input[name=selected_amount]');
            var cb = $(this).is(':checked');
            var id = parseInt($(this).attr('id'));
            invoices[id] = $(this).attr('name');
            tmp_amount[id] = amount;
            if(cb == true){
                sum = sum + amount;
                s_amount.val(sum.toFixed(2));
                id = id + 1;
                $('#'+id).removeAttr('disabled');
                console.log(id);
                tmp = sum;
            }else{
                id = id + 1;
                for(var i = id; i <= $('table input[type=checkbox]').length; i++){
                     $('#'+i).attr('disabled',true);
                     $('#'+i).prop('checked',false);
                }
                for(var i = id-1; i <= $('table input[type=checkbox]').length; i++){
                      tmp_amount.splice(id-1,1);
                      invoices.splice(id-1,1);
                }
                sum = eval(tmp_amount.join('+'));
                if(sum === undefined || sum === NaN || sum === ''){
                    sum = 0.00;
                }
                tmp = sum;
                s_amount.val(sum.toFixed(2));
            }
                if(tmp === undefined || tmp === NaN || tmp === ''){
                    tmp = 0.00;
                }else{
                    tmp = tmp - parseFloat($('input[name=payment_account]').val());
                    if(tmp < 0){
                       tmp = 0;
                }
            }
            console.log(invoices);
            console.log(tmp_amount);
            $('input[name="balance"]').val(tmp.toFixed(2));
            console.log(tmp);

        });
        function curbal(data){

        }
        function getbal(id){
            var result = '';
            $.ajax({
                url:"<?php echo base_url($this->session->userdata('forajax').'/getbalance'); ?>",
                method:'post',
                async: false,
                data:{ 'invoice_id' : id },
                dataType:'json',
                success: function (data) {
                    console.log(data[0].invoice_balance);
                    result =  data[0].invoice_balance;
                },
                error: function (xhr){

                }
            });
            return result;
        }
        
        $(function(){           
            $('input[name=payment_account]').keyup(function(){  
                calculateTotal($(this).val());
            });
            $('input[name=payment_account]').blur(function(){  
                if($('input[name=payment_account]').val() == ''){
                    $('input[name=payment_account]').val(0);
                }
                calculateTotal($(this).val());
            });
        });

        $(':input[type=number]').on('mousewheel', function(e){
            e.preventDefault();
        });

        function calculateTotal(src) {
            var sum = 0;
            var bal = $('input[name="selected_amount"]').val();

            if(!isNaN(src) && src.length!=0) {
                sum += parseFloat(src);
            }
            $('input[name=totalcost]').val(sum.toFixed(2));
            bal = bal - sum;
            if(bal < 0 || sum < 0){
                bal = 0;
            }
            $('input[name="balance"]').val(bal.toFixed(2));
        }

        var validator = $( "#payment_process_form" ).validate();

        $('#process_payment').click(function(){
            if(parseFloat($('#payment_process_form input[name=payment_account]').val()) == 0){
                validator.showErrors({
                  "payment_account": "Please Enter an amount."
                });
                notifymsg('danger','<b>Error:</b> Can\'t Process Transaction.');
            }else if(parseFloat($('#payment_process_form input[name=selected_amount]').val()) < parseFloat($('#payment_process_form input[name=payment_account]').val())){
                validator.showErrors({
                  "payment_account": "Oops! The amount you enter is to high from the amount you selected"
                });
                notifymsg('danger','<b>Error:</b> Can\'t Process Transaction.');
            }else{
                if($('#payment_process_form').valid() == true){
                    console.log(invoices.length - 1);
                    console.log(tmp_amount);
                    var balance = 0; var lastins = 0;
                    for(var i = 1; i <= invoices.length - 1; i++){
                        if(invoices.length-1 == i){
                            balance = parseFloat($('#payment_process_form input[name=balance]').val());
                            lastins = 1;
                        }else{
                            lastins = 0;
                            balance = 0;
                        }
                        $.ajax({
                            url:"<?php echo base_url($this->session->userdata('forajax').'/process_payment'); ?>",
                            method:'post',
                            data:$('#payment_process_form').serialize()+'&'+$.param({ 'invoice_id': invoices[i], 'bal': balance , 'last_ins': lastins, 'acct_name':  localStorage.acct_name , 'acct_num':  localStorage.acct_num }),
                            dataType:'json',
                            success: function (data) {
                                if(data.err == 1){
                                    notifymsg('danger',data.msg);
                                }else{
                                    $('#search_payment').trigger('click');
                                    getrecnum();
                                    notifymsg('success','<b>Success</b>: Data Saved.');
                                }
                            },
                            beforeSend: function(){
                                 $('#process_payment').attr('disabled',true);
                                 $('#loading-icon-process').show();
                            },
                            complete: function(){
                                 //$('#receipt').modal('show');
                                 $('#process_payment').removeAttr('disabled');
                                 $('#loading-icon-process').hide();
                            }
                        });
                    }
                }
            }
        });

        $('#search_payment').click(function(){
                getrecnum();
                invoices = []; tmp = 0; sum = 0;
                $('#payment_process_form')[0].reset();
                $('#payment_process_form input[name=receipt_date]').val(new Date().toJSON().slice(0,10));
                $("#payment_process_form #process_payment").removeAttr('disabled');
                $.ajax({
                    url:"<?php echo base_url($this->session->userdata('forajax').'/search_payment'); ?>",
                    method:'post',
                    data:$('#search_payment_form').serialize(),
                    dataType:'json',
                    success: function (data) {
                      $('#tbl_payments').html('');
                      console.log(data.length);
                      var tmp = '';
                      var count = 1;
                      var disable = '';
                      var paid_amount = 0;
                      if(data !== 'No results found.' ){
                        localStorage.acct_name = data[0].acct_name;
                        localStorage.acct_num = data[0].account_num;
                        $.each(data,function(i,item){
                            paid_amount = 0;
                            paid_amount = parseFloat(data[i].invoice_total) - parseFloat(data[i].invoice_balance);
                            disable = '';
                            if(count != 1){
                                disable = 'disabled';
                            }
                            if(data[i].invoice_balance > 0){
                                tmp += "<tr><td class='invoice_id' style='display: none;'>"+data[i].invoice_id+"</td><td align='right'>"+ data[i].invoice_num +"</td><td>"+ data[i].rec_name +"</td><td>"+ data[i].invoice_date +"</td><td>"+ data[i].due_date +"</td><td align='right'>"+ data[i].invoice_total +"</td><td align='right'>"+ paid_amount +"</td><td class='amount' align='right'>"+ data[i].invoice_balance +"</td><td align='center'><input "+disable+" type='checkbox' id='"+count+"' name='"+data[i].invoice_id+"'></td></tr>"
                                count++;
                            }
                          });
                      }else{
                                 tmp = "<tr align='center'><td colspan='8'>No Balance.</td></tr>";
                                 $("#payment_process_form #process_payment").attr('disabled',true); 
                            }
                      $('#tbl_payments').html(tmp);
                    },
                    beforeSend: function(){
                        
                    },
                    complete: function(){
                        
                    }
                });
        });

        function getrecnum(){
            $.ajax({
                url:"<?php echo base_url($this->session->userdata('forajax').'/getrecnum'); ?>",
                method:'get',
                dataType:'json',
                success: function (data) {
                    $('#payment_process_form input[name=receipt_number]').val(data[0].val);
                }
            });
        }

        $("#search_payment_form").validate({
             rules: {
                 acct_name: {
                    lettersonly: true
                 },
                 acct_num: {
                    number: true
                 }
             }
        });

        $('#payment_process_form').validate({
            rules: {
                payment_account: {
                    required: true,
                    number: true
                },
                payment_type: {
                    required: true
                },
                receipt_date: {
                    required: true
                },
            }
        });
    });
    </script>